package com.hannesdorfmann.mosby3.mvi.integrationtest.slice;

import com.hannesdorfmann.mosby3.mvi.integrationtest.ResourceTable;
import com.hannesdorfmann.mosby3.mvi.integrationtest.lifecycle.fraction.RetainingFractionAbility;
import com.hannesdorfmann.mosby3.mvi.integrationtest.lifecycle.fraction.SimpleRetainingMviLifecycleFraction;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.fraction.Fraction;
import ohos.aafwk.content.Intent;

import java.util.Optional;

public class RetainingFractionAbilitySlice extends AbilitySlice {

    private static final String TAG = "Test-Fragment";
    static volatile RetainingFractionAbilitySlice slice;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        slice = getInstance();
        super.setUIContent(ResourceTable.Layout_ability_lifecycle);

        SimpleRetainingMviLifecycleFraction f = new SimpleRetainingMviLifecycleFraction();
        ((RetainingFractionAbility) getAbility()).getFractionManager()
                .startFractionScheduler()
                .replace(ResourceTable.Id_container, f)
                .pushIntoStack(TAG)
                .submit();
    }

    public static RetainingFractionAbilitySlice getInstance(){
        if(RetainingFractionAbilitySlice.slice == null){
            RetainingFractionAbilitySlice.slice = new RetainingFractionAbilitySlice();
        }
        return  RetainingFractionAbilitySlice.slice;
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    public SimpleRetainingMviLifecycleFraction getFragment(){
        Optional<Fraction> fractionOptional = ((RetainingFractionAbility)getAbility()).getFractionManager().getFractionByTag(TAG);
        return (SimpleRetainingMviLifecycleFraction) fractionOptional.get();
    }

    public static void pressBackButton() {
        getInstance().getUITaskDispatcher().syncDispatch(new Runnable() {
            @Override public void run() {
                getInstance().onBackPressed();
            }
        });
    }
}
